<template>
    <view class="">
        <oreder-header
            :type="'out'"
            :placeholder="'输入采购单号/出库单/收货人'"
            @searchFn="searchFn"
            @doFilter="doFilter"></oreder-header>
        <view class="main">
            <mescroll-uni
                ref="mescrollRef"
                @init="mescrollInit"
                :height="listHeight"
                :down="downOption"
                @down="downRefresh"
                :up="upOption"
                @up="getData">
                <view class="wrapper">
                    <view class="outOrder" v-for="(item, index) in datas" :key="index">
                        <view class="title">采购单号：{{ item.BuyOrderNo }}</view>
                        <view
                            class="datainfo"
                            v-for="(subitem, i) in item.StockOutList"
                            :key="i"
                            @click="
                                goUrl(
                                    '/pages_supplier/packet/outOrder/detail?buyOrdId=' +
                                        item.BuyOrderId +
                                        '&outId=' +
                                        subitem.StockOutId,
                                )
                            ">
                            <view
                                ><view>出库单号：</view><view>{{ subitem.StockOutSn }}</view></view
                            >
                            <view
                                ><view>出库时间：</view><view>{{ subitem.StockOutTime }}</view></view
                            >
                            <view
                                ><view>收货人：</view
                                ><view>{{ subitem.ReceiveMan }} {{ subitem.ReceiveContactTel }}</view></view
                            >
                            <view
                                ><view>配送方式：</view
                                ><view>{{ subitem.ExpressName }} | {{ subitem.ExpressNo }}</view></view
                            >
                            <view class="bottombtn" @click.stop="print(subitem)"><view>打印面单</view></view>
                        </view>
                    </view>
                </view>
                <!-- 	<view class="footer">
				<view class="all btn">打印全部出库单</view>
				<view class="btn">打印全部面单</view>
			</view> -->
            </mescroll-uni>
            <uni-popup ref="popReturnTip" type="center" :animation="false" :mask-click="true">
                <view class="pop-return-box">
                    <view class="bluelist">
                        <view :key="index" v-for="(item, index) in devices">
                            <view class="blue" @click="onConn(item)">{{ item.name }}</view>
                        </view>
                        <view class="bluetip mescroll-upwarp" v-if="bluetipShow"
                            ><view class="mescroll-rotate"></view>搜索中</view
                        >
                        <view class="bluebtn" @click="searchBle">搜索蓝牙</view>
                    </view>
                </view>
            </uni-popup>
        </view>
    </view>
</template>
<script>
var tsc = require("@/pages_supplier/components/gprint/tsc.js")
var esc = require("@/pages_supplier/components/gprint/esc.js")
import orederHeader from "@/pages_supplier/components/order/order-header.vue"
import storage from "@/uni-sub-base/utils/storage.js"
import { getElementHeight } from "@/uni-sub-base/utils/elementUtil.js"
import { GetBuyOrderStockOutList } from "@/pages_supplier/service/api/buyOrder.js"
export default {
    components: {
        orederHeader,
    },
    data() {
        return {
            bluetipShow: false,
            devices: [],
            currDev: null,
            connId: "",
            devicesData: [],
            datas: [],
            data: [],
            productList: [],
            param: {},
            downOption: {
                use: true,
            },
            listHeight: "",
            requestData: {
                searchKey: "",
                startTime: "",
                buyOrdSn: "",
                endTime: "",
                state: 0,
                workerId: 0,
            },
            printerItem: {},
        }
    },
    onLoad(e) {
        if (e.OrderNo) {
            this.requestData.buyOrdSn = e.OrderNo
        }
        if (storage.getCache("devices")) {
            this.devicesData = storage.getCache("devices")
        }
    },
    mounted() {
        this.getListHeight()
        //#ifndef MP
        this.refresh(this.requestData)
        //#endif
    },
    onUnload() {
        storage.removeCache("devices")
        this.destroyed()
    },
    methods: {
        goUrl(url) {
            this.easyGoTo(url)
        },
        getListHeight(element) {
            //获取商品高度
            getElementHeight(this, ".main", (e) => {
                this.listHeight = e + "px"
                this.loadOk = true
            })
        },
        //获取列表数据
        getData(page) {
            let param = this.param
            param.pageSize = page.size
            param.pageIndex = page.num
            GetBuyOrderStockOutList(param).then((res) => {
                if (res.State == 1) {
                    this.mescroll.endBySize(res.Data.length, res.RecordAmout)
                    this.datas = this.datas.concat(res.Data)
                } else {
                    this.mescroll.endBySize(0, 0)
                }
            })
        },
        //刷新
        refresh(requestData) {
            console.log(requestData)
            this.downRefresh(requestData, true)
        },
        //刷新
        downRefresh(requestData, isSetParam = false) {
            this.datas = []
            if (isSetParam) {
                this.param = requestData
            }
            this.mescroll.resetUpScroll()
        },
        //搜索
        searchFn(searchKey) {
            this.requestData.buyOrdSn = searchKey
            this.refresh(this.requestData)
        },
        //筛选
        doFilter(data) {
            this.requestData.startTime = data.startDate ? data.startDate + " 00:00:00" : ""
            this.requestData.endTime = data.endDate ? data.endDate + " 23:59:59" : ""
            this.refresh(this.requestData)
        },
        print(item) {
            this.printerItem = item
            console.log(this.printerItem)
            if (this.devicesData.length > 0) {
                this.initBule()
                // this.senBleLabel()
            } else {
                this.$refs.popReturnTip.open()
            }
        },
        destroyed: function () {
            console.log("destroyed----------")
            if (this.connId != "") {
                uni.closeBLEConnection({
                    deviceId: this.connId,
                    success(res) {
                        console.log(res)
                    },
                })
            }
        },
        initBule() {
            var that = this
            uni.openBluetoothAdapter({
                success(res) {
                    console.log("打开 蓝牙模块")
                    console.log(res)
                    uni.getBluetoothAdapterState({
                        success: function (res) {
                            console.log(res)
                            if (res.available) {
                                that.senBleLabel()
                            } else {
                                storage.removeCache("devices")
                                console.log("本机蓝牙不可用")
                            }
                        },
                    })
                },
                fail(errCode) {
                    if (errCode.code == 10001) {
                        that.easyToast("请先开启蓝牙")
                        storage.removeCache("devices")
                    }
                },
            })
        },
        searchBle() {
            var that = this
            that.bluetipShow = true
            console.log("initBule")
            uni.openBluetoothAdapter({
                success(res) {
                    console.log("打开 蓝牙模块")
                    console.log(res)
                    that.onDevice()
                    uni.getBluetoothAdapterState({
                        success: function (res) {
                            console.log(res)
                            if (res.available) {
                                if (res.discovering) {
                                    that.stopFindBule()
                                }
                                //搜索蓝牙
                                //开始搜寻附近的蓝牙外围设备
                                console.log("开始搜寻附近的蓝牙外围设备")
                                uni.startBluetoothDevicesDiscovery({
                                    success(res) {
                                        console.log(res)
                                    },
                                })
                            } else {
                                storage.removeCache("devices")
                                console.log("本机蓝牙不可用")
                            }
                        },
                    })
                },
                fail(errCode) {
                    if (errCode.code == 10001) {
                        that.easyToast("请先开启蓝牙")
                        storage.removeCache("devices")
                    }
                },
            })
        },
        onDevice() {
            console.log("监听寻找到新设备的事件---------------")
            var that = this
            //监听寻找到新设备的事件
            uni.onBluetoothDeviceFound(function (devices) {
                console.log("--------------new-----------------------" + JSON.stringify(devices))
                var re = JSON.parse(JSON.stringify(devices))
                console.log(re.devices[0].name + "  " + re.devices[0].deviceId)
                let name = re.devices[0].name
                if (name != "未知设备" && name != "") {
                    let deviceId = re.devices[0].deviceId
                    that.devices.push({
                        name: name,
                        deviceId: deviceId,
                        services: [],
                    })
                }
                console.log(that.devices)
            })
        },

        stopFindBule() {
            console.log("停止搜寻附近的蓝牙外围设备---------------")
            uni.stopBluetoothDevicesDiscovery({
                success(res) {
                    console.log(res)
                },
            })
        },
        onConn(item) {
            var that = this
            console.log("连接蓝牙---------------" + item.deviceId)
            let deviceId = item.deviceId
            uni.createBLEConnection({
                deviceId: deviceId,
                complete(res) {
                    if (res.errMsg == "createBLEConnection:ok") {
                        that.easyToast("连接蓝牙-[" + item.name + "]--成功")
                        that.connId = deviceId
                        that.currDev = item
                        setTimeout(function () {
                            that.getBLEServices(deviceId)
                        }, 2000)
                    } else {
                        console.log(res)
                    }
                    //连接成功 关闭搜索
                    that.stopFindBule()
                },
                fail(error) {
                    console.log(error)
                },
            })
        },

        getBLEServices(_deviceId) {
            var that = this
            let deviceId = _deviceId
            console.log("获取蓝牙设备所有服务(service)。---------------")

            uni.getBLEDeviceServices({
                // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                deviceId: deviceId,
                complete(res) {
                    console.log(res)
                    let serviceId = ""

                    for (var s = 0; s < res.services.length; s++) {
                        console.log(res.services[s].uuid)
                        let serviceId = res.services[s].uuid
                        uni.getBLEDeviceCharacteristics({
                            // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                            deviceId: deviceId,
                            // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                            serviceId: serviceId,
                            success(res) {
                                var re = JSON.parse(JSON.stringify(res))

                                console.log("deviceId = [" + deviceId + "]  serviceId = [" + serviceId + "]")
                                for (var c = 0; c < re.characteristics.length; c++) {
                                    if (re.characteristics[c].properties.write == true) {
                                        let uuid = re.characteristics[c].uuid
                                        console.log(
                                            " deviceId = [" +
                                                deviceId +
                                                "]  serviceId = [" +
                                                serviceId +
                                                "] characteristics=[" +
                                                uuid,
                                        )

                                        for (var index in that.devices) {
                                            if (that.devices[index].deviceId == deviceId) {
                                                that.devices[index].services.push({
                                                    serviceId: serviceId,
                                                    characteristicId: uuid,
                                                })
                                                break
                                            }
                                        }
                                        console.log(JSON.stringify(that.devices))
                                        storage.setCache("devices", that.devices)
                                        that.devicesData = that.devices
                                    }
                                }
                                that.$refs.popReturnTip.close()
                                that.bluetipShow = false
                            },
                        })
                    }
                },
                fail(res) {
                    console.log(res)
                },
            })
        },
        senBlData(deviceId, serviceId, characteristicId, uint8Array) {
            console.log(
                "************deviceId = [" +
                    deviceId +
                    "]  serviceId = [" +
                    serviceId +
                    "] characteristics=[" +
                    characteristicId +
                    "]",
            )
            var uint8Buf = Array.from(uint8Array)
            function split_array(datas, size) {
                var result = {}
                var j = 0
                for (var i = 0; i < datas.length; i += size) {
                    result[j] = datas.slice(i, i + size)
                    j++
                }
                console.log(result)
                return result
            }
            var sendloop = split_array(uint8Buf, 20)
            // console.log(sendloop.length)
            function realWriteData(sendloop, i) {
                var data = sendloop[i]
                if (typeof data == "undefined") {
                    return
                }
                console.log("第【" + i + "】次写数据" + data)
                var buffer = new ArrayBuffer(data.length)
                var dataView = new DataView(buffer)
                for (var j = 0; j < data.length; j++) {
                    dataView.setUint8(j, data[j])
                }
                uni.writeBLECharacteristicValue({
                    deviceId,
                    serviceId,
                    characteristicId,
                    value: buffer,
                    success(res) {
                        realWriteData(sendloop, i + 1)
                    },
                })
            }
            var i = 0
            realWriteData(sendloop, i)
        },
        senBleLabel() {
            //标签模式
            let currDev = this.devicesData[0]
            let deviceId = currDev.deviceId
            let serviceId = currDev.services[0].serviceId
            let characteristicId = currDev.services[0].characteristicId
            var command = tsc.jpPrinter.createNew()
            // console.log(command)
            command.setSize(76, 130)
            command.setGap(2)
            command.setCls()
            command.setText(20, 150, "TSS24.BF2", 1, 1, "No." + this.printerItem.StockOutSn)
            // command.setQR(10, 50, "L", 5, "A", "977767937@qq.com")
            command.setBar(20, 200, 128, 120, 0, 2, 2, this.printerItem.ExpressNo)
            command.setText(20, 370, "TSS24.BF2", 1, 1, "配送单号：" + this.printerItem.ExpressNo)
            command.setText(20, 500, "TSS24.BF2", 3, 3, "寄")
            command.setText(120, 500, "TSS24.BF2", 1, 1, this.printerItem.SendMan + "    " + this.printerItem.SendTel)
            command.setTextauto(120, 550, "TSS24.BF2", 1, 1, this.printerItem.SendAddress)
            command.setText(20, 700, "TSS24.BF2", 3, 3, "收")
            command.setText(
                120,
                700,
                "TSS24.BF2",
                1,
                1,
                this.printerItem.ReceiveMan + "    " + this.printerItem.ReceiveContactTel,
            )
            command.setTextauto(120, 750, "TSS24.BF2", 1, 1, this.printerItem.Address)
            command.setPagePrint()
            this.senBlData(deviceId, serviceId, characteristicId, command.getData())
        },
    },
}
</script>

<style lang="scss">
.main {
    padding: 0rpx 0 0rpx 0;
}
.wrapper {
    padding: 24rpx 0 0rpx 0;
}
.footer {
    width: 750rpx;
    height: 120rpx;
    background: #ffffff;
    box-shadow: 0px -2rpx 6rpx 0px rgba(0, 0, 0, 0.1);
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 99;
    display: flex;
    justify-content: center;
    align-items: center;
    .btn {
        width: 304rpx;
        height: 80rpx;
        background: $app-color-main;
        border-radius: 40rpx;
        font-size: 28rpx;
        color: #ffffff;
        margin: 0 23rpx;
    }
    .all {
        background: #222a42;
    }
}
.outOrder {
    margin: 0rpx 24rpx 24rpx 24rpx;
    background: #ffffff;
    .title {
        font-size: 28rpx;
        color: $color-gray-1;
        font-weight: bold;
        height: 88rpx;
        display: flex;
        align-items: center;
        padding: 0 24rpx;
        position: relative;
        border-bottom: 1rpx solid $uni-border-bottom-color;
        &::after {
            content: "";
            position: absolute;
            width: 6rpx;
            height: 38rpx;
            background: $app-color-main;
            left: 0;
        }
    }
    .datainfo {
        line-height: 2;
        padding: 12rpx 24rpx 24rpx 24rpx;
        border-bottom: 2rpx solid $uni-border-bottom-color;
        &:last-child {
            border: none;
        }
        & > view {
            display: flex;
            align-items: center;
            font-size: 28rpx;
            color: $color-gray-1;
            & > view:first-child {
                color: $color-gray-3;
                width: 150rpx;
            }
        }
        .bottombtn {
            display: flex;
            justify-content: flex-end;
            view {
                width: 160rpx;
                height: 64rpx;
                background: #ffffff;
                border-radius: 32rpx;
                border: 1rpx solid $app-color-main;
                font-size: 28rpx;
                color: $app-color-main !important;
                display: flex;
                justify-content: center;
                align-items: center;
            }
        }
    }
}
.bluelist {
    text-align: center;
    .blue {
        border-radius: 29rpx;
        border: 1rpx solid #0081ff;
        color: #0081ff;
        padding: 10rpx 0;
        margin-bottom: 20rpx;
    }
    .bluebtn {
        width: 304rpx;
        height: 80rpx;
        line-height: 80rpx;
        text-align: center;
        background: $app-color-main;
        border-radius: 40rpx;
        font-size: 28rpx;
        color: #ffffff;
        margin: 0 auto;
    }
}
/*旋转进度条 */
.mescroll-upwarp {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    padding: 10rpx 0;
    color: $color-gray-2;
}
.mescroll-upwarp .mescroll-rotate {
    display: inline-block;
    width: 32rpx;
    height: 32rpx;
    border-radius: 50%;
    border: 2rpx solid gray;
    border-bottom-color: transparent !important; /*已在style设置border-color,此处需加 !important*/
    vertical-align: middle;
    margin-right: 10rpx;
}

/* 旋转动画 */
.mescroll-upwarp .mescroll-rotate {
    animation: mescrollUpRotate 0.6s linear infinite;
}

@keyframes mescrollUpRotate {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}
</style>
